package cn.spark.study.core;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.broadcast.Broadcast;

import java.util.Arrays;
import java.util.List;

/**
 * 广播变量
 *
 * @author jun.zhang6
 * @date 2020/11/6
 */
public class BroadcastVariable {

    public static void main(String[] args) {
        SparkConf sparkConf = new SparkConf()
                .setAppName("BroadcastVariable")
                .setMaster("local");
        final int factor = 3;

        JavaSparkContext sc = new JavaSparkContext(sparkConf);


        final Broadcast<Integer> broadcast = sc.broadcast(factor);

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        JavaRDD<Integer> numbersRdd = sc.parallelize(numbers);

        JavaRDD<Integer> multipleNumbersRdd = numbersRdd.map(new Function<Integer, Integer>() {
            @Override
            public Integer call(Integer v) throws Exception {
                Integer factor = broadcast.value();
                return factor * v;
            }
        });

        multipleNumbersRdd.foreach(new VoidFunction<Integer>() {
            @Override
            public void call(Integer v) throws Exception {
                System.out.println(v);
            }
        });
    }
}
